﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TechTalk.SpecFlow;

namespace Goblinfactory.SpecUtils
{
    public static class TableHelper
    {

        private static readonly string[] emptyStrings = new string[] {};

        public static string[] GetColumn(this Table table, string header)
        {
            return GetColumn(table,null, header);
        }

        public static string[] GetColumn(this Table table, int column)
        {
            return GetColumn(table, (int?) column, null);
        }


         private static string[] GetColumn(Table table, int? column, string header)
        {
            // TODO replace with specification attributes to require one or the other
            // I hate this type of checking because it's not clear from the method interface that this is going to happen.
            if (column!=null && !string.IsNullOrEmpty(header)) throw new ArgumentNullException("header","either column or header is required.");
            if (table.Rows == null || table.RowCount == 0) return emptyStrings;
             int numcols = table.RowCount;
            if (column > numcols) throw new ArgumentOutOfRangeException("column", column, "column no cannot be > than header columns.");

            var cells = new string[numcols];
             int i = 0;
            foreach (var row in table.Rows)
            {
                // must check data type because while SpecFlow.TableRow already checks data
                // we can't rely on that always being the case.
                var content = column.HasValue ? row[column.Value] ?? string.Empty : row[header] ?? string.Empty;
                cells[i++] = content;
            }
             return cells.ToArray();
        }


    } // class
} // namespace
